﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Smartec.Accounts.Camel.AMS.WebApp.Models;
using Telerik.Web.Mvc;
using System.Web.Security;
using Smartec.Accounts.Camel.AMS.Model.Entities;
using Smartec.Accounts.Camel.AMS.Model.Facades;
using System.Web.Routing;

namespace Smartec.Accounts.Camel.AMS.WebApp.Controllers
{
    public class SystemUsersController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        //
        // GET: /SystemUserViews/
        [CustomAuthorize(Action = "View")]
        public ActionResult Index(string RoleName)
        {
            ViewBag.RoleName = RoleName == null ? "All" : RoleName;

            List<SiteUser> siteUsers = new List<SiteUser>();
            return View(siteUsers);
        }

        [GridAction]
        public ActionResult _index(string RoleName)
        {
            string roleName = RoleName == null ? "All" : RoleName;

            IEnumerable<SiteUser> allSiteUsers = SiteUserFacade.FindAllSiteUsers();

            List<SiteUser> siteUsers = new List<SiteUser>();
            foreach (MembershipUser user in Membership.GetAllUsers())
            {
                Guid userId = (Guid)Membership.GetUser(user.UserName).ProviderUserKey;
                SiteUser siteUser = allSiteUsers.Where(o => o.ID == userId).FirstOrDefault();
                if (roleName == "All" || Roles.IsUserInRole(user.UserName, roleName))
                {
                    siteUser.Roles = string.Join(", ", Roles.GetRolesForUser(user.UserName));
                    siteUser.Email = user.UserName;
                    siteUsers.Add(siteUser);
                }
            }

            return View(new GridModel<SiteUser>
            {
                Data = siteUsers
            });
        }


        //
        // GET: /SystemUserViews/Create
        [CustomAuthorize(Action = "Add")]
        public ActionResult Create()
        {
            ViewBag.AllRoles = Roles.GetAllRoles();
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        
        // POST: /SystemUserViews/Create

        [HttpPost]
        public ActionResult Create(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                DateTime? startDate = Request.Form["StartDateValue"].ToFormatedDate();
                DateTime? endDate = Request.Form["EndDateValue"].ToFormatedDate();
               
                string userRoles = Request.Form["userrole"];
                List<string> userRolesList = new List<string>();
                if (!string.IsNullOrEmpty(userRoles))
                {
                    userRolesList = userRoles.Split(',').ToList();
                }

                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.UserName);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    Guid id = (Guid)Membership.GetUser(model.UserName).ProviderUserKey;
          
                    SiteUser siteUser = new SiteUser()
                    {
                        ID = id,
                        DisplayName_EN = model.DisplayName_EN,
                        DisplayName_AR = model.DisplayName_AR,
                        StartDate = startDate,
                        EndDate = endDate,
                        IsActive = model.IsActive
                    };

                    SiteUserFacade.Add(siteUser);
                    SiteUserFacade.Save();

                    if (userRolesList.Count > 0)
                    {
                        Roles.AddUserToRoles(Membership.GetUser(model.UserName).UserName, userRolesList.ToArray());
                    }

                    //FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.AllRoles = Roles.GetAllRoles();
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        //private static void GetFormatedDate(string _startDate,string _endDate, out DateTime? startDate, out DateTime? endDate)
        //{
        //    startDate = null;
        //    if (!string.IsNullOrEmpty(_startDate))
        //    {
        //        string[] startDateParts = _startDate.Split('-');
        //        startDate = new DateTime(Int32.Parse(startDateParts[2]), Int32.Parse(startDateParts[1]), Int32.Parse(startDateParts[0]));
        //    }

        //    endDate = null;
        //    if (!string.IsNullOrEmpty(_endDate))
        //    {
        //        string[] endDateParts = _endDate.Split('-');
        //        endDate = new DateTime(Int32.Parse(endDateParts[2]), Int32.Parse(endDateParts[1]), Int32.Parse(endDateParts[0]));
        //    }
        //}

        
         //GET: /SystemUserViews/Edit/5
        [CustomAuthorize(Action = "Edit")]
        public ActionResult Edit(string id)
        {
            Guid userId = new Guid(id);
            MembershipUser membershipUser = Membership.GetUser(userId);
            SiteUser siteUser = SiteUserFacade.GetSiteUser(userId);
            ViewBag.AllRoles = Roles.GetAllRoles();
            ViewBag.UserRoles = Roles.GetRolesForUser(membershipUser.UserName);
            ViewBag.Email = membershipUser.UserName;

            ViewBag.IsCurrentUser = HttpContext.User.Identity.Name == membershipUser.UserName;

            return View(siteUser);
        }

        
         //POST: /SystemUserViews/Edit/5

        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            Guid userId = new Guid(id);
            MembershipUser membershipUser = Membership.GetUser(userId);
            SiteUser siteUser = SiteUserFacade.GetSiteUser(userId);

            bool isCurrentUser = HttpContext.User.Identity.Name == membershipUser.UserName;

            try
            {
                DateTime? startDate = Request.Form["StartDateValue"].ToFormatedDate();
                DateTime? endDate = Request.Form["EndDateValue"].ToFormatedDate();

                UpdateModel(siteUser);
                siteUser.StartDate = startDate;
                siteUser.EndDate = endDate;
                if (!isCurrentUser)
                {
                    if (collection["IsActive"] == null)
                    {
                        siteUser.IsActive = false;
                    }
                    else
                    {
                        siteUser.IsActive = true;
                    }
                }

                SiteUserFacade.Save();

                if (!isCurrentUser)
                {
                    string userroles = collection["userrole"];
                    List<string> userrolesList = new List<string>();
                    if (!string.IsNullOrEmpty(userroles))
                    {
                        userrolesList = userroles.Split(',').ToList();
                    }

                    List<string> originaluserRoles = new List<string>();
                    string[] originaluserRolesArr = Roles.GetRolesForUser(membershipUser.UserName);
                    if (originaluserRolesArr.Length > 0)
                    {
                        originaluserRoles = originaluserRolesArr.ToList();
                    }

                    IEnumerable<string> removedUserRoles = originaluserRoles.Where(o => !userrolesList.Contains(o));
                    IEnumerable<string> addedUserRoles = userrolesList.Where(o => !originaluserRoles.Any(t => t == o));

                    if (removedUserRoles.Count() > 0)
                    {
                        Roles.RemoveUserFromRoles(membershipUser.UserName, removedUserRoles.ToArray());
                    }

                    if (addedUserRoles.Count() > 0)
                    {
                        Roles.AddUserToRoles(membershipUser.UserName, addedUserRoles.ToArray());
                    }

                }
                return RedirectToAction("Index");
            }
            catch
            {
                ViewBag.AllRoles = Roles.GetAllRoles();
                ViewBag.UserRoles = Roles.GetRolesForUser(membershipUser.UserName);
                ViewBag.Email = membershipUser.UserName;
                ViewBag.IsCurrentUser = HttpContext.User.Identity.Name == membershipUser.UserName;
                return View(siteUser);
            }
        }

        [CustomAuthorize(Action = "Delete")]
        [HttpPost]
        public ActionResult Delete(string id)
        {
            Guid userId = new Guid(id);
            MembershipUser membershipUser=Membership.GetUser(userId);
            SiteUser siteUser = SiteUserFacade.GetSiteUser(userId);
            bool isCurrentUser = HttpContext.User.Identity.Name == membershipUser.UserName;
            if (isCurrentUser)
                return Json(new { itemName = siteUser.DisplayName, success = false });
            try
            {
                // Validation and deletion code
                Membership.DeleteUser(membershipUser.UserName, true);
            }
            catch
            {
                return Json(new { itemName = siteUser.DisplayName, success = false });
            }

            return Json(new { success = true });
        }

        // **************************************
        // URL: /SystemUser/ResetPassword
        // **************************************

        [CustomAuthorize(Action = "Edit")]
        public ActionResult ResetPassword(string id)
        {
            Guid userId = new Guid(id);
            MembershipUser membershipUser = Membership.GetUser(userId);
            ResetPasswordModel resetPasswordModel = new ResetPasswordModel();
            resetPasswordModel.UserName = membershipUser.UserName;
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(resetPasswordModel);
        }

        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ResetPassword(model.UserName, model.NewPassword))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

    }
}
